package com.cy.demo1.service.impl;

import com.cy.demo1.entity.User;
import com.cy.demo1.mapper.UserMapper;
import com.cy.demo1.service.IUserService;
import com.cy.demo1.service.ex.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public void reg(User user) {
        String username = user.getUserName();
        //判断用户名是否注册过
        User result = userMapper.findByUsername(username);
        if(result != null) {
            throw new UsernameDuplicatedException("用户名被占用");
        }

        //执行注册业务功能的实现
        Integer rows = userMapper.insert(user);
        if (rows != 1) {
            throw new InsertException("用户注册过程 中产生未知异常");
        }
    }

    @Override
    public User login(String username, String password) {
        //根据用户名称来查询用户的数据是否存在，如果不存在则抛出异常
        User result = userMapper.findByUsername(username);
        if (result == null) {
            throw new UserNotFoundException("用户数据不存在");
        }
        //检测用户的密码是否匹配
        //1.先获取到数据库中的密码
        String dbPassword = result.getPassword();
        //2.和用户传递过来的密码进行比较
        if (!password.equals(dbPassword)){
            throw new PasswordNotMatchException("用户密码错误");
        }

        //调用mapper层的findByUser来查询用户数据
        User user = new User();
        user.setUserId(result.getUserId());
        user.setUserName(result.getUserName());
        user.setPassword(result.getPassword());

        //将当前的用户数据返回
        return user;
    }

    @Override
    public User getByUid(Integer userId) {
        User result = userMapper.findByUid(userId);
        if(result == null) {
            throw new UserNotFoundException("用户数据不存在");
        }

        return result;
    }

    @Override
    public void changeInfo(Integer userId, String userName, String password) {
        User result = userMapper.findByUid(userId);
        if(result == null) {
            throw new UserNotFoundException("用户数据不存在");
        }
        User result2 = userMapper.findByUsername(userName);
        if(result2 != null && result2.getUserId() != userId) {
            throw new UsernameDuplicatedException("用户名被占用");
        }
        User user = new User();
        user.setUserId(userId);
        user.setUserName(userName);
        user.setPassword(password);

        Integer rows = userMapper.updateInfoByUid(user);
        if(rows != 1) {
            throw new UpdateException("更新时数据产生未知异常");
        }
    }


}
